package org.jeecg.modules.meter.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.ComUtil;
import org.jeecg.common.util.PushWxMessage;
import org.jeecg.config.GetRequestJsonUtils;
import org.jeecg.config.JsonMapper;
import org.jeecg.config.Sm4Util;
import org.jeecg.entity.meter.MeterOrder;
import org.jeecg.modules.message.service.ISysMessageService;
import org.jeecg.modules.meter.service.IMeterControlSwitchService;
import org.jeecg.modules.meter.service.IMeterOrderService;
import org.jeecg.modules.system.entity.TemplateData;
import org.jeecg.vo.meter.MeterSwitchRespVo;
import org.jeecg.vo.pay.FFTPayNotify;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 水电表充值账单 - 对外接口
 *
 * @author liurui
 * @version v1.0
 * @date 2018年11月15日
 */
@Controller
@RequestMapping(value = "b/meter/foreign/order")
@Slf4j
public class ForeignMeterOrderController {


    @Autowired
    private IMeterOrderService meterOrderService;
    @Autowired
    private IMeterControlSwitchService meterControlSwitchService;
    @Autowired
    private ISysMessageService messageService;
    @Value("${pay.fftEncryptKey}")
    private String fftEncryptKey; //付费通加密key


    @RequestMapping(value = "getEncryptKeyJson")
    @ResponseBody
    @ApiOperation("加密")
    public String getEncryptKeyJson(HttpServletRequest request, HttpServletResponse response){
        String str = null;
        try {
            str =  GetRequestJsonUtils.getEncryptEcb(request,fftEncryptKey);
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }
       return str;
    }

    /**
     * 支付回调接口
     *
     * @return
     */
    @RequestMapping(value = "meterPayNotify")
    @ResponseBody
    @ApiOperation("仪表付费通回调接口")
    public String meterPayNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            com.alibaba.fastjson.JSONObject jsonObject = GetRequestJsonUtils.getRequestJsonObject(request,fftEncryptKey);
            log.info("仪表付费通回调接口参数：{}",jsonObject);
            FFTPayNotify stu= JSON.parseObject(jsonObject.toJSONString(), FFTPayNotify.class);
            Result<MeterOrder> result = meterOrderService.meterPayNotify(stu);
            //更新短信
            List<MeterSwitchRespVo> meterSwitchRespVoList = result.getResult().getSwitchRespVoList();


            if (result.isSuccess()){
                meterControlSwitchService.controlSwitchMeter(result.getResult().getSwitchRespVoList());
            }
            // 开电票
            meterOrderService.meterBlueInvoice(result.getResult());

            return Sm4Util.encryptEcb(fftEncryptKey,"200success");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Sm4Util.encryptEcb(fftEncryptKey,"error");

    }

    /**
     * 光大支付回调接口
     *
     * @return
     */
    @RequestMapping(value = "meterPayCEBNotify")
    @ResponseBody
    @ApiOperation("仪表光大回调接口")
    public void meterPayCEBNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            BufferedReader reader = request.getReader();
            String json = reader.readLine();
            reader.close();
            JSONObject jsonObject = JSONObject.fromObject(json);
            int code = jsonObject.getInt("code");
            int status = jsonObject.getInt("status");
            JSONObject data = JSONObject.fromObject(jsonObject.getString("data"));
            if (code == 0){
                FFTPayNotify stu = new FFTPayNotify();
                stu.setOrderId(data.getString("out_trade_no"));
                stu.setPaymentAmt(data.getString("amount"));
                stu.setPaymentTime(data.getString("payment_at"));
                stu.setTransNo(data.getString("transaction_number"));
                Result<MeterOrder> result = meterOrderService.meterPayNotify(stu);
                    log.info("-------推送------");
                    try {
                        Date date = new Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String createdate = sdf.format(date);
                        String cn = stu.getOrderId();
                        String openId =  meterOrderService.getOpenId(cn);
                        Map<String, TemplateData> pushDate = new HashMap<>();
                        pushDate.put("date2", new TemplateData(createdate) );//充值时间
                        pushDate.put("amount3", new TemplateData(stu.getPaymentAmt()));//实付金额
                        pushDate.put("character_string7", new TemplateData(cn));//订单号
                        pushDate.put("thing8", new TemplateData("电费充值")); // 备注
                        PushWxMessage pushWxMessage = new PushWxMessage();
                        String message = pushWxMessage.pushOneUser(openId, "kTB_-kmUemyOly7ONQ3ITk3xfaODnfDYYK90tEFj5-Q", pushDate);
                       log.info("推送结果",message);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    //      messageService.updateSmsLevel(result.getResult().getSwitchRespVoList());
                if (result.isSuccess()){
                    meterControlSwitchService.controlSwitchMeter(result.getResult().getSwitchRespVoList());
                }
                // 开电票
                meterOrderService.meterBlueInvoice(result.getResult());
            }
            Writer out = response.getWriter();
            Map<String, Object> map = new HashMap<String, Object>();
            if (code == 0 && status == 0) {
                map.put("status", 0);
                map.put("msg", "");
                map.put("code", 0);
            } else {
                map.put("status", 1);
                map.put("msg", "");
                map.put("code", 0);
            }
            out.write(JsonMapper.getInstance().toJson(map));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     *
     * @param payUrl  请求地址
     * @param request 请求json串
     * @return
     */
    @RequestMapping(value = "testCreateOrder")
    @ApiOperation("测试仪表付费通下单接口")
    @ResponseBody
    public Result testCreateOrder(String payUrl,@RequestBody String request){
        log.info("模拟水电加密参数:{}",request);
        String cipher = Sm4Util.encryptEcb(fftEncryptKey, request);
        log.info("模拟加密后:{}",cipher);
        com.alibaba.fastjson.JSONObject payRes;
        try {
            payRes = ComUtil.doPost(payUrl+"/ori/createOrder",cipher,fftEncryptKey);
            log.info("模拟水电返回json========="+ payRes);
        }catch (Exception e){
            log.error("模拟水电缴费调用下单接口异常:{}",e);
            return Result.error("模拟水电缴费调用银行支付接口繁忙！");
        }
        return Result.ok(payRes);
    }




}